import { useState, useEffect, FC, SyntheticEvent, ChangeEvent } from 'react'
import { Scrollbars } from 'react-custom-scrollbars'
import type { ColumnsType, ColumnType } from 'antd/es/table'
import { BaseOptionType, DefaultOptionType } from 'antd/lib/select'
import { IData, IResponseCodeType, PagingSize, IRoleAdminListModel, IDepartmentAdminInfo, IMemberAdminListModel, IMemberAdminInfo, IMemberAdminAddInfo, IAllDepartmentListModel, DictionaryTypeModal, IFileClassModel, IFileClassInfo, IFileClassAttrInfo, IFileClassAttrModel } from '@/models/common'
import XlButtonFC from '@/components/xlbutton/xlbutton'
import XlModalFC from '@/components/xlmodal/xlmodal'
import util from '@/utils/util'
import { useAppDispatch, useAppSelector } from '@/store'
import { EditOutlinedIcon, DeleteOutlinedIcon, DownOutlinedIcon, UserAddOutlinedIcon } from '@/models/icons'
import * as api from '@/api'
import { Avatar, Layout, Row, Tree, Col, Modal, Space, Table, Card, Form, Input, Select, TreeSelect } from 'antd'
import './fileclassadmin.scss'
interface ColumnsDataType {
  [name: string]: string
}
export interface IViewModel {
  selectedKeys: React.Key[]
  selectedClass: IFileClassInfo
  classTreeData: IFileClassInfo[]
  classUpdateModalOpen: boolean,
  classUpdateRow: ColumnsDataType

  attrUpdateModalOpen: boolean
  /**
   * 当前修改分类属性信息
   */
  attrUpdateRow: ColumnsDataType
  pageLoading: boolean
  /**
   * 表格数据
   */
  attrTableList: ColumnsDataType[]
  /**
  * 当前页码
  */
  page: number
  /**
   * 每页数量
   */
  pageSize: number
  /**
   * 是否还有下一页
   */
  hasNextPage: boolean

  notAuth: boolean
  dictOptions: DefaultOptionType[]
}
const Index: FC = () => {
  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      selectedKeys: [],
      selectedClass: {},
      classTreeData: [],
      classUpdateModalOpen: false,
      classUpdateRow: {
        class_id: "",
        class_name: "",
        is_customer: "",
      },

      attrUpdateModalOpen: false,
      attrUpdateRow: {
        is_customer: "",
        name: "",
        id: "",
        comment: "",
        dictionary_id: "",
        dictionary_name: ""
      },
      pageLoading: false,
      attrTableList: [],
      page: 1,
      pageSize: PagingSize.PageSize,
      hasNextPage: false,

      notAuth: false,
      dictOptions: [],
    }
  })

  useEffect(() => {
  }, [])


  const events = {
    //分类选中
    onClassSelect(selectedKeys: React.Key[], info: any) {
      // console.log('selectedKeys:', selectedKeys, info);
      const { ViewModel } = data
      ViewModel.selectedKeys = selectedKeys
      ViewModel.selectedClass = selectedKeys.length == 0 ? {} : info.node
      ViewModel.page = 1
      setData({ ...data })
      methods.requestAttrList()
    },
    //分类新增
    onClickAddClass() {
      let record = {
        class_id: "",
        class_name: "",
        is_customer: ""
      }
      events.resetClassUpdateRow(true, record)
    },
    //分类编辑
    onClickEditClass(e: SyntheticEvent, record: IFileClassInfo) {
      util.cancelBubble(e)
      events.resetClassUpdateRow(true, record)
    },
    //分类删除
    onClickDeleteClass(e: SyntheticEvent, record: IFileClassInfo) {
      util.cancelBubble(e)
      Modal.confirm({
        title: '删除',
        centered: true,
        closable: true,
        content: '确认删除该分类吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestDeleteClass(record.class_id as string)
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onUpdateClassNameChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.classUpdateRow.class_name = e.target.value
      setData({ ...data })
    },
    onClassUpdateRowOk() {
      const { ViewModel } = data
      if (!ViewModel.classUpdateRow.class_name) {
        util.alertTip('请输入分类名称')
        return
      }
      if (ViewModel.classUpdateRow.class_id) {
        methods.requestUpdateClass()
      } else {
        methods.requestAddClass()
      }
    },
    onClassUpdateRowCancel() {
      events.resetClassUpdateRow(false)
    },
    resetClassUpdateRow(open: boolean, record?: IFileClassInfo) {
      const { ViewModel } = data
      ViewModel.classUpdateRow.class_id = record ? record.class_id! : ''
      ViewModel.classUpdateRow.class_name = record ? record.class_name! : ''
      ViewModel.classUpdateRow.is_customer = record ? record.is_customer! : ''
      ViewModel.classUpdateModalOpen = open
      setData({ ...data })
    },

    //成员新增
    onClickAddRow() {
      const { ViewModel } = data
      ViewModel.attrUpdateRow.name = ''
      ViewModel.attrUpdateRow.id = ''
      ViewModel.attrUpdateRow.comment = ''
      ViewModel.attrUpdateRow.dictionary_id = ''
      ViewModel.attrUpdateRow.is_customer = ''
      ViewModel.attrUpdateRow.dictionary_name = ''
      ViewModel.attrUpdateModalOpen = true
      setData({ ...data })
    },
    //成员编辑
    onClickEditRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      const { ViewModel } = data
      ViewModel.attrUpdateRow.name = record.name
      ViewModel.attrUpdateRow.id = record.id
      ViewModel.attrUpdateRow.comment = record.comment
      ViewModel.attrUpdateRow.dictionary_id = record.dictionary_id
      ViewModel.attrUpdateRow.is_customer = record.is_customer
      ViewModel.attrUpdateRow.dictionary_name = record.dictionary_name
      ViewModel.attrUpdateModalOpen = true
      setData({ ...data })
    },
    //成员删除
    onClickDeleteRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      Modal.confirm({
        title: '删除',
        centered: true,
        closable: true,
        content: '确认删除该属性吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestDeleteAttr(record.id)
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onUpdateAttrNameChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.attrUpdateRow.name = e.target.value
      setData({ ...data })
    },
    onUpdateDictionaryTypeChange(value: string) {
      const { ViewModel } = data
      ViewModel.attrUpdateRow.dictionary_id = value
      setData({ ...data })
    },
    onUpdateAttrCommentChange(e: ChangeEvent<HTMLTextAreaElement>) {
      const { ViewModel } = data
      ViewModel.attrUpdateRow.comment = e.target.value
      setData({ ...data })
    },
    onAttrUpdateRowOk() {
      const { ViewModel } = data
      if (!ViewModel.attrUpdateRow.name) {
        util.alertTip('请输入属性名称')
        return
      }
      if (!ViewModel.attrUpdateRow.dictionary_id) {
        util.alertTip('请选择数据字典')
        return
      }
      if (ViewModel.attrUpdateRow.id) {
        methods.requestUpdateAttr()
      } else {
        methods.requestAddAttr()
      }
    },
    onAttrUpdateRowCancel() {
      const { ViewModel } = data
      ViewModel.attrUpdateModalOpen = false
      setData({ ...data })
    },
    onClickLoadMore() {
      const { ViewModel } = data
      if (ViewModel.hasNextPage) {
        ViewModel.page = ViewModel.page + 1
        ViewModel.pageLoading = true
        setData({ ...data })
        methods.requestAttrList()
      }
    },
  }
  const methods = {
    /**
     * 加载字典
     */
    async requestDictionaryTypeList() {
      const { ViewModel } = data
      let res = await api.common.getAllDictionaryTypes<DictionaryTypeModal>(null)
      const { code, data: DictionaryTypeData, message } = res
      if (code == IResponseCodeType.Success) {
        let { type_list = [] } = DictionaryTypeData
        ViewModel.dictOptions = type_list.map((o) => {
          return {
            label: o.type_label,
            value: o.id
          }
        })
        setData({ ...data })
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 加载全部分类
     */
    async requestClassAdminList() {
      const { ViewModel } = data
      let res = await api.common.getFileClassList<IFileClassModel>(null)
      let { code, message, data: classTreeData, } = res
      if (code == IResponseCodeType.Success) {
        let { class_list = [] } = classTreeData
        ViewModel.classTreeData = [...class_list]
        setData({ ...data })
      } else if (code == IResponseCodeType.NotAuth) {
        ViewModel.notAuth = true
        setData({ ...data })
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 删除分类
     * @param id 
     */
    async requestDeleteClass(class_id: string) {
      let res = await api.common.deleteFileClass<null>({
        class_id,
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        const { ViewModel } = data
        const { classTreeData } = ViewModel
        for (let i = 0; i < classTreeData.length; i++) {
          if (classTreeData[i].class_id === class_id) {
            classTreeData.splice(i, 1);
            break;
          }
        }
        ViewModel.selectedKeys = []
        ViewModel.classTreeData = [...classTreeData]
        setData({ ...data })
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 新增分类
     */
    async requestAddClass() {
      const { ViewModel } = data
      let res = await api.common.addFileClass({
        class_name: ViewModel.classUpdateRow.class_name,
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.classUpdateModalOpen = false
        setData({ ...data })
        methods.requestClassAdminList()
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 编辑分类
     */
    async requestUpdateClass() {
      const { ViewModel } = data
      let res = await api.common.editFileClass({
        class_name: ViewModel.classUpdateRow.class_name,
        class_id: ViewModel.classUpdateRow.class_id,
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        const { classTreeData } = ViewModel
        util.departmentForEach(classTreeData, (o) => {
          if (o.class_id == ViewModel.classUpdateRow.class_id) {
            o.class_name = ViewModel.classUpdateRow.class_name
          }
        })
        ViewModel.classTreeData = [...classTreeData]
        ViewModel.classUpdateModalOpen = false
        setData({ ...data })
      } else {
        util.alertTip(message)
      }
    },

    /**
     * 加载分类属性
     */
    async requestAttrList() {
      const { ViewModel } = data
      let { attrTableList, page, pageSize, selectedKeys } = ViewModel
      if (selectedKeys.length == 0) {
        return
      }
      let res = await api.common.getClassAttributeList<IFileClassAttrModel>({
        class_id: selectedKeys[0] as string,
      })
      const { code, data: classAttrAdminData, message } = res
      if (code == IResponseCodeType.Success) {
        let { attribute_list = [] } = classAttrAdminData
        if (page == 1) {
          attrTableList = []
        }
        ViewModel.attrTableList = [...attrTableList, ...attribute_list]
        if (attribute_list.length < pageSize) {
          ViewModel.hasNextPage = false
        } else {
          ViewModel.hasNextPage = true
        }
      } else {
        util.alertTip(message)
      }
      ViewModel.pageLoading = false
      setData({ ...data })
    },
    /**
     * 新增分类属性
     */
    async requestAddAttr() {
      const { ViewModel } = data
      let res = await api.common.addClassAttribute<IFileClassAttrInfo>({
        class_id: ViewModel.selectedClass.class_id,
        name: ViewModel.attrUpdateRow.name,
        dictionary_id: ViewModel.attrUpdateRow.dictionary_id,
        comment: ViewModel.attrUpdateRow.comment,
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.attrUpdateModalOpen = false
        ViewModel.page = 1
        setData({ ...data })
        methods.requestAttrList()
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 更新分类属性
     */
    async requestUpdateAttr() {
      const { ViewModel } = data
      let res = await api.common.editClassAttribute({
        id: ViewModel.attrUpdateRow.id,
        class_id: ViewModel.selectedClass.class_id,
        name: ViewModel.attrUpdateRow.name,
        dictionary_id: ViewModel.attrUpdateRow.dictionary_id,
        comment: ViewModel.attrUpdateRow.comment,
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.attrUpdateModalOpen = false
        ViewModel.page = 1
        setData({ ...data })
        methods.requestAttrList()
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 删除分类属性
     * @param user_id 
     */
    async requestDeleteAttr(id: string) {
      let res = await api.common.deleteClassAttribute<null>({
        id
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        data.ViewModel.page = 1
        methods.requestAttrList()
      } else {
        util.alertTip(message)
      }
    },
    createColumns() {
      const columns: ColumnsType<ColumnsDataType> = [
        {
          title: '属性名称',
          align: "left",
          key: 'name',
          dataIndex: 'name',
          width: 150,
        },
        {
          title: '数据字典',
          align: "left",
          key: 'dictionary_name',
          dataIndex: 'dictionary_name',
          width: 150,
        },
        {
          title: '属性说明',
          align: "left",
          key: 'comment',
          dataIndex: 'comment',
          width: 250,
        },
        {
          title: '操作',
          align: "center",
          key: 'action',
          fixed: "right",
          width: 130,
          render: (_, record, index) => (
            <Space size={4}>
              {
                record.is_customer == '1' ? <>
                  <XlButtonFC type='primary' size='small' onClick={() => events.onClickEditRow(_, record, index)}>
                    修改
                  </XlButtonFC>
                  <XlButtonFC type='primary' size='small' onClick={() => events.onClickDeleteRow(_, record, index)}>
                    删除
                  </XlButtonFC>
                </> : null
              }
            </Space>
          ),
        }
      ]
      return columns
    },
    renderPage() {
      if (data.ViewModel.notAuth) {
        return null
      }
      return <Layout className='fileclassadmin-body'>
        <Layout.Sider theme='light' className='fileclassadmin-sider' width={300}>
          <Scrollbars autoHide>
            <Row className='add-class-wrap' align='middle'>
              <XlButtonFC type='primary' onClick={events.onClickAddClass}>添加分类</XlButtonFC>
            </Row>
            <Col className='class-tree-wrap'>
              <Tree
                autoExpandParent
                blockNode
                onSelect={events.onClassSelect}
                treeData={data.ViewModel.classTreeData}
                selectedKeys={data.ViewModel.selectedKeys}
                fieldNames={{
                  title: "class_name",
                  key: "class_id",
                }}
                titleRender={
                  (nodeData) => {
                    return <Row justify='space-between' align='middle' className='title-render-wrap'>
                      <Col className='title'>{nodeData.class_name}</Col>
                      {
                        nodeData.is_customer == '1' ? <Row align='middle' gutter={8} className='title-action-wrap'>
                          <Col title='编辑' onClick={(e) => { events.onClickEditClass(e, nodeData) }}><EditOutlinedIcon /></Col>
                          <Col title='删除' onClick={(e) => { events.onClickDeleteClass(e, nodeData) }}><DeleteOutlinedIcon /></Col>
                        </Row> : null
                      }
                    </Row>
                  }
                }
              />
            </Col>
          </Scrollbars>
        </Layout.Sider>
        <Layout.Content className='fileclassadmin-content'>
          <Card
            title={<strong>{data.ViewModel.selectedClass.class_name}</strong>}
            style={{ display: data.ViewModel.selectedKeys?.length == 0 ? 'none' : 'block' }}
          >
            <Col className='member-list-wrap'>
              {/* 按钮操作区域 */}
              <Row align='middle' justify='space-between' className='buttonGroupWrap' gutter={[0, 10]}>
                <Col>
                  <Space size={6}>
                    <XlButtonFC type='primary' onClick={events.onClickAddRow}>添加属性</XlButtonFC>
                  </Space>
                </Col>
                <Col className='count'>
                  {data.ViewModel.hasNextPage ? '已部分加载' : '已全部加载'}，共{data.ViewModel.attrTableList.length}个
                </Col>
              </Row>
              {/* 表格区域 */}
              <Row className='tableWrap'>
                <Col className={['tableContent', data.ViewModel.hasNextPage ? 'hasTableContent' : 'noTableContent'].join(" ")}>
                  <Table
                    scroll={{
                      x: '100%',
                      y: data.ViewModel.hasNextPage ? 'calc(100vh - 355px)' : 'calc(100vh - 280px)'
                    }}
                    loading={data.ViewModel.pageLoading}
                    tableLayout='fixed'
                    rowKey='id'
                    pagination={false}
                    columns={methods.createColumns()}
                    dataSource={data.ViewModel.attrTableList}
                  />
                </Col>

                {
                  data.ViewModel.hasNextPage ? <Row className='loadmore-wrap' onClick={events.onClickLoadMore}>
                    <Col>点击加载更多</Col>
                    <Row><DownOutlinedIcon className='loadmore-icon' /></Row>
                  </Row> : null
                }
              </Row>
            </Col>
          </Card>
          {/* 添加/修改分类弹出框 */}
          <XlModalFC
            open={data.ViewModel.classUpdateModalOpen}
            onOk={events.onClassUpdateRowOk}
            onCancel={events.onClassUpdateRowCancel}
            title='新增/修改分类'
            destroyOnClose
          >
            <Form
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 17 }}
              autoComplete="off"
            >
              <Form.Item
                label="分类名称"
                required
              >
                <Input value={data.ViewModel.classUpdateRow.class_name} onChange={events.onUpdateClassNameChange} allowClear placeholder='请输入分类名称' />
              </Form.Item>
            </Form>
          </XlModalFC>
          {/* 添加/修改属性弹出框 */}
          <XlModalFC
            open={data.ViewModel.attrUpdateModalOpen}
            onOk={events.onAttrUpdateRowOk}
            onCancel={events.onAttrUpdateRowCancel}
            title='新增/修改属性'
            destroyOnClose
          >
            <Form
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 17 }}
              autoComplete="off"
            >
              <Form.Item
                label="分类名"
                required
              >
                <Input value={data.ViewModel.selectedClass.class_name} disabled />
              </Form.Item>
              <Form.Item
                label="属性名称"
                required
              >
                <Input type='text' value={data.ViewModel.attrUpdateRow.name} onChange={events.onUpdateAttrNameChange} placeholder='请输入属性名称' allowClear />
              </Form.Item>
              <Form.Item
                label="数据字典"
                required
              >
                <Select
                  value={data.ViewModel.attrUpdateRow.dictionary_id || undefined}
                  placeholder='请选择数据字典'
                  allowClear
                  style={{ width: '100%' }}
                  onChange={events.onUpdateDictionaryTypeChange}
                  options={data.ViewModel.dictOptions}
                />
              </Form.Item>
              <Form.Item
                label="属性说明"
              >
                <Input.TextArea value={data.ViewModel.attrUpdateRow.comment} onChange={events.onUpdateAttrCommentChange} allowClear placeholder='请输入属性说明' />
              </Form.Item>
            </Form>
          </XlModalFC>
        </Layout.Content>
      </Layout>
    }
  }

  return methods.renderPage()
}
export default Index
